package com.web.itemGetway.GlobalFilter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.web.itemGetway.jwtUtils.jwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class GlobalFilters implements GlobalFilter, Ordered {
    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    jwtUtils jwtUtils;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        log.info("Request URI: {} ;METHOD: {}", request.getURI(), request.getMethod());

        String path = exchange.getRequest().getURI().getPath();
        if (path.contains("/login") || path.contains("/regin")|| path.contains("/wcCheck")|| path.contains("/service")) {
            log.info("登录注册微信请求，直接放行");
            if(path.contains("/service")){
                log.info("这是压测放行");
            }
            return chain.filter(exchange);
        } else {
            List<String> tokenList = request.getHeaders().get("token");
            if (tokenList != null && !tokenList.isEmpty()) {
                log.info("已经携带了jwt放行 JWT: {}", tokenList.get(0));
                String token = tokenList.get(0);
                try {
                    jwtUtils.parseJwt(token);
                } catch (Exception e) {
                    log.info("jwt已经失效: {}", e.getMessage());
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                log.info("jwt令牌通过校验");
                ServerWebExchange webExchange = exchange.mutate().request(builder -> builder.header("token", token)).build();
                return chain.filter(webExchange);
            } else {
                log.info("未携带jwt");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
